package com.hxzy.controller.userinfo;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.common.BaseServlet;
import com.hxzy.common.ResultAjax;
import com.hxzy.util.BeanValidatorUtil;
import com.hxzy.entity.UserInfo;
import com.hxzy.service.UserInfoService;
import com.hxzy.service.impl.UserInfoServiceImpl;
import org.mindrot.jbcrypt.BCrypt;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 * @Description:
 * @Author: ykj
 * @Date: 2022/3/1 16:29
 */
@WebServlet(urlPatterns = "/web/tojson")
public class AddJsonServlet extends BaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        try {
            //搜集参数
            UserInfo userInfo = super.CollectiongParameterToJSON(req, UserInfo.class);
            //验证参数
            Set<String> validator = BeanValidatorUtil.validator(UserInfo.class, userInfo);
            //验证通过
            if (validator.isEmpty()){
                //加密
                String hashpw = BCrypt.hashpw(userInfo.getLoginPwd(), BCrypt.gensalt());
                userInfo.setLoginPwd(hashpw);

                //service
                UserInfoService userInfoService=new UserInfoServiceImpl();
                int insert = userInfoService.insert(userInfo);
                ResultAjax resultAjax=null;
                if (insert >0) {
                   resultAjax= ResultAjax.success();
                }else {
                   resultAjax= ResultAjax.error();
                }
                super.render(resp, JSONObject.toJSONString(resultAjax));
            }else {
                //验证失败
                String message = validator.iterator().next();
                ResultAjax resultAjax = ResultAjax.error(message);
                super.render(resp, JSONObject.toJSONString(resultAjax));
            }
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}
